package com.wanchuang.shengfubao.module.main;

import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wanchuang.shengfubao.R;
import com.wanchuang.shengfubao.base.BaseFragment;
import com.wanchuang.shengfubao.help.GlideHelper;
import com.wanchuang.shengfubao.help.PermissionHelper;
import com.wanchuang.shengfubao.net.Apis;
import com.wanchuang.shengfubao.net.NetworkManager;
import com.wanchuang.shengfubao.net.interfaces.OnRequestCallBack;
import com.wanchuang.shengfubao.proto.Memberinviter;
import com.wanchuang.shengfubao.utils.ImageUtil;
import com.wanchuang.shengfubao.utils.SaveViewToImageUtil;
import com.google.protobuf.InvalidProtocolBufferException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class QrFragment extends BaseFragment {
    Unbinder unbinder;
    @BindView(R.id.tv_qr)
    FrameLayout tvQr;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_bg)
    ImageView ivBg;
    @BindView(R.id.iv_qr)
    ImageView ivQr;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.rlQrBg)
    RelativeLayout rlQrBg;
    @BindView(R.id.iv_share)
    TextView ivShare;
    private List<Memberinviter.get_my_qrcode_inviter.List> listList = new ArrayList<>();
    private int currentBg = 0;

    private PopupWindow mPopupWindow;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_qr;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initView() {
        loadData();
    }

    private void loadData() {
        NetworkManager.INSTANCE.post(Apis.get_my_qrcode_inviter, new OnRequestCallBack() {


            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Memberinviter.get_my_qrcode_inviter data = Memberinviter.get_my_qrcode_inviter.parseFrom(response);
                listList = data.getImgBgListList();
                tvName.setText(data.getMemberName());

                GlideHelper.INSTANCE.loadImage(ivBg, data.getImgBgListList().get(0).getAdvCode());
                GlideHelper.INSTANCE.loadImage(ivHead, data.getMemberAvatar());
                GlideHelper.INSTANCE.loadImage(ivQr, data.getQrcodeUrl());
                Log.e("ivQr", "onOk: "+data.getQrcodeUrl() );


                float left = Float.valueOf(data.getImgBgListList().get(0).getLeft()) / 100;
                float top = Float.valueOf(data.getImgBgListList().get(0).getTop()) / 100;

                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(tvQr.getLayoutParams());
                lp.setMargins((int) (getPMWith() * left), (int) (ivBg.getHeight() * top), 0, 0);
                tvQr.setLayoutParams(lp);


                int offset = (tvQr.getMeasuredWidth() - tvName.getWidth()) / 2;
                Log.e("mango", tvName.getMeasuredWidth() + "");
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(tvName.getLayoutParams());
                layoutParams.addRule(RelativeLayout.BELOW, tvQr.getId());
                layoutParams.setMargins(offset + (int) (getPMWith() * left), 0, 0, 0);
                tvName.setLayoutParams(layoutParams);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }

    @Override
    protected void init() {
        ivShare.setOnClickListener(view -> {
            more();
        });
    }


    private int getPMWith() {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }


    private void changeBg() {
        int size = listList.size();
        int i = currentBg + 1;
        if (i > size - 1)  // 加载第一个
        {
            currentBg = 0;
            GlideHelper.INSTANCE.loadImage(ivBg, listList.get(0).getAdvCode());
        } else {
            currentBg = i;
            GlideHelper.INSTANCE.loadImage(ivBg, listList.get(i).getAdvCode());
        }
        float left = Float.valueOf(listList.get(currentBg).getLeft()) / 100;
        float top = Float.valueOf(listList.get(currentBg).getTop()) / 100;
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(tvQr.getLayoutParams());
        lp.setMargins((int) (getPMWith() * left), (int) (ivBg.getHeight() * top), 0, 0);
        tvQr.setLayoutParams(lp);
        int offset = (tvQr.getMeasuredWidth() - tvName.getWidth()) / 2;
        Log.e("mango", tvName.getMeasuredWidth() + "");
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(tvName.getLayoutParams());
        layoutParams.addRule(RelativeLayout.BELOW, tvQr.getId());
        layoutParams.setMargins(offset + (int) (getPMWith() * left), 0, 0, 0);
        tvName.setLayoutParams(layoutParams);
    }


    private void more() {
        if (mPopupWindow == null) {
            View popView = View.inflate(mContext, R.layout.more_layout, null);
            mPopupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setOutsideTouchable(true);
            ColorDrawable dw = new ColorDrawable(Color.parseColor("#00000000"));
            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            mPopupWindow.setBackgroundDrawable(dw);
            popView.findViewById(R.id.save_image).setOnClickListener(view -> {
                PermissionHelper.getInstance().getPermission(getActivity(), new PermissionHelper.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(rlQrBg);
                        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getString(R.string.app_name);
                        String fileName = System.currentTimeMillis() + ".jpg";
                        boolean b = ImageUtil.saveImageToGallery(mContext, viewBitmap, storePath, fileName);
                        if (b) {
                            showToast("保存成功");
                            mPopupWindow.dismiss();
                        }

                    }

                    @Override
                    public void onFail() {
                        showToast("获取权限失败");
                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);


            });
            popView.findViewById(R.id.change_bg).setOnClickListener(view -> {
                changeBg();
                mPopupWindow.dismiss();
            });
        }
        mPopupWindow.showAsDropDown(ivShare);
    }
}